﻿#ifndef JSONPATH_H
#define JSONPATH_H

#include <QObject>
#include <QJsonDocument>
#include <QVariant>
#include <QJsonValue>
class JsonPathReader : public QObject {
    Q_OBJECT

public:
    JsonPathReader(QObject *parent = nullptr);
    JsonPathReader(const QByteArray &byte, QObject *parent = nullptr);
    void parse(const QByteArray &byte);

    QJsonValue jsonValue(const char *cformat, ...);
    static QJsonValue JsonValue(const QJsonValue &var, const char *cformat, ...);
    QVariant value(const char *cformat, ...);
    QVariant valueList(const char *cformat, ...);
    static QVariant Value(QJsonValue var, const char *cformat, ...);
    int arrayCount(const char *cformat, ...);

    QJsonParseError::ParseError errorType();
    QString errString();

    static QStringList path2List(const QString &path);
    static QJsonValue _jsonValue(QJsonValue var, const QString &path);

private:
    QJsonValue _jsonValue(const QString &path);
    int _arrayCount(const QString &path);
    static QByteArray toJson(const QJsonValue &var);
private:
    QJsonValue json;
    QJsonParseError err;
};

class JsonPathWriter : public QObject {
    Q_OBJECT

public:
    JsonPathWriter(QObject *parent = nullptr);
    void parse(const QByteArray &byte);

    bool setValue(const QString &path, const QVariant &var);
    bool append(const QString &path, const QMap<QString, QVariant> &obj, bool doClear = false);
    QByteArray toJson();
private:
    QVariant *mapValuePtr(const QString &path);

private:
    QVariant json;
};

#endif // JSONPATH_H
